package com.expdatacloud.controller.file;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 *  用于文件上传下载
 * */
@Controller
@RequestMapping("/file")
public class FileController {

    @PostMapping(value = "/uploadFile")
    @ResponseBody
    public HashMap uploadPicture(@RequestParam("file") MultipartFile file, HttpServletRequest servletRequest)throws IOException {
        //上传文件路径
        String path = servletRequest.getServletContext().getRealPath("/uploadFile");
        System.out.println("文件名称"+file.getOriginalFilename());

        HashMap<String,String> res = new HashMap<>();

        //上传文件名
        String fileName = file.getOriginalFilename();//上传文件的真实名称

        //去除特殊字符
        String regEx="[\n`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
        fileName = fileName.replaceAll(regEx,"");

        //String suffixName = name.substring(name.lastIndexOf("."));//获取后缀名
        //String hash = Integer.toHexString(new Random().nextInt());//自定义随机数（字母+数字）作为文件名
        //String fileName = hash + suffixName;
        // 判断文件是否已存在
        File file1 = new File(path+"/"+fileName);
        if(file1.exists()){
            res.put("code","E");
            res.put("msg","存在相同名字的文件,请重命名后再次上传!");
            res.put("fileName",fileName);
            return res;
        }

        File filepath = new File(path, fileName);
        //判断路径是否存在，没有就创建一个
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        //将上传文件保存到一个目标文档中
        File tempFile = new File(path + File.separator + fileName);
        file.transferTo(tempFile);


        res.put("code","S");
        res.put("msg","上传成功");
        res.put("fileName",fileName);
        return res;
    }

    @GetMapping(value = "/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response){
        try {
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + fileName);
            String path = request.getSession().getServletContext().getRealPath("/uploadFile/"+fileName);
            File file =new File(path);
            // 如果文件名存在，则进行下载
            if (file.exists()) {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download the song successfully!");
                } catch (Exception e) {
                    System.out.println("Download the song failed!");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件下载失败");
        }
    }
}
